
let iosocket = io.connect();

iosocket.on('connect', function () {
    iosocket.emit('set nickname',user_name);
    // $('#chat_user_name').text(user_name);
    iosocket.on('webrtc',async function (data) {
        if(data.sdp){
            if(data.sdp.type=='offer'){
                await createRTCPeerConnection(data.id,chatting_user=='multi_chat_option'? createRemoteVideo(data.id):video_p2p,false);
                if(pcs[data.id]){
                    try{
                        await pcs[data.id].setRemoteDescription(data.sdp);
                        let localStream = await navigator.mediaDevices.getUserMedia({audio: true, video: true});
                        localStream.getTracks().forEach(track => pcs[data.id].addTrack(track, localStream));
                        mediaStreamTracks = localStream.getTracks();
                        video_me.srcObject = localStream;
                        video_p2p.hidden = video_me.hidden = false;
                        isInVideo = true;//设置状态
                    }catch (e){
                        console.log('创建流失败！');
                        quitOutVideo();
                    }
                    await pcs[data.id].setLocalDescription(await pcs[data.id].createAnswer());
                    iosocket.emit('webrtc',{sdp: pcs[data.id].localDescription,id:data.id});
                    console.log('创建成功！发送answer！！');
                } else {
                    console.log('获取到sdp offer，但创建流失败！');
                    alert('获取到sdp offer，但创建流失败！');alert('创建流失败！');quitOutVideo();
                    iosocket.emit('webrtc',null);//退出
                }
            }else if(data.sdp.type=='answer'){
                console.log('收到answer！！');//alert('收到answer！！');
                    await pcs[data.id].setRemoteDescription(data.sdp);
            } else {
                console.log('解析SDP类型输错！！');
            }
        }else if(data.candidate) {
            await pcs[data.id].addIceCandidate(data.candidate);
        }
    });
    iosocket.on('flash list', function(msgs) {//刷新用户列表,列表中id用socket.id
        $('#user_list').empty();//先清空
        user_list=msgs.list;
        my_room=msgs.room;
        delete msgs.list[iosocket.id];//删除自己的记录，如果有的话
        // addUserLi(iosocket.id,user_name);//顶部是群聊
        for(let key in msgs.list) addUserLi(key,msgs.list[key]);
        $('#user_num').text(msgs.num);
    });
    iosocket.on('news', function(msgs) {//用户变更
        if(msgs.what=="new") {//新用户加入聊天室
            if($('#' + msgs.id).length == 0){
                addUserLi(msgs.id, msgs.name);
                user_list[msgs.id]=msgs.name;
            }
        } else{//有用户退出聊天室
            $('#' + msgs.id).remove();
            if(isInVideo){
                let v=$('#video_' + msgs.id);
                if (v) {
                    v.parent().remove();
                    pcs[msgs.id].close();
                    delete pcs[msgs.id];
                }
            }
            delete user_list[msgs.id];
        }
        $('#user_num').text(msgs.num);//更新人数
    });
    iosocket.on('chat_p2p', function(msgs) {
        switch (msgs.what) {
            case "request":
                console.log('request from: '+user_list[msgs.id]);
                $('#btn-dialogBox').dialogBox({
                    hasClose: true, hasBtn: true,
                    confirmValue: '同意', cancelValue: '没空', title: '私聊请求',
                    content: user_list[msgs.id]+"请求与你私聊，是否同意？",
                    confirm: function(){//受邀方同意
                        iosocket.emit('chat_p2p',{what: 'reply',id: msgs.id,val: 'yes'});
                    },
                    cancel:function(){//不同意
                        iosocket.emit('chat_p2p',{what: 'reply',id: msgs.id,val:'no'});
                    }
                });
                break;
            case "reply":
                console.log('reply from: '+msgs.id);
                if(msgs.val=='yes'){
                    //对方同意
                    console.log('对方是：'+msgs.id+user_list[msgs.id]);
                    // $('#'+msgs.id).css('background','#d7dede');
                    // $('#'+chatting_user).css('background','#ffffff');
                    // chatting_user=msgs.id;
                    $('#chat_user_name').text(user_list[msgs.id]);
                    makeAutoDialog(user_list[msgs.id]+"已和你建立私聊！",1500);
                }else makeAutoDialog(
                    (msgs.val=='no')?
                            "哈哈哈，"+user_list[msgs.id]+"不愿意和你私聊呢！"
                            : user_list[msgs.id]+"正在和别人私聊，没空理你！",
                    1500);
                break;
            case "set_room":
                my_room=msgs.val;
                $('#chat_list').empty();//清空聊天记录
                iosocket.emit('chat_p2p',{what:'set_room',val:my_room});
                let id=msgs.id==iosocket.id? msgs.id2:msgs.id;//找对方id
                $('#'+id).css('background','#d7dede');
                $('#'+chatting_user).css('background','#ffffff');
                $('#chat_user_name').text(user_list[id]);
                chatting_user=id;//更改列表样式
                break;
            case "leave_out":
                if(isInVideo) quitOutVideo();
                $('#multi_chat_option').css('background','#d7dede');
                $('#'+chatting_user).css('background','#ffffff');
                chatting_user='multi_chat_option';
                $('#chat_user_name').text('群聊天室');

                iosocket.emit('chat_p2p',{what:'leave_out',val:my_room});//回群聊
                my_room=msgs.val;

                makeAutoDialog('通知', "已离开私聊！",1500);
                break;
            case "video":
                if(msgs.isQuit){
                    quitOutVideo();
                    makeAutoDialog('对方已经挂断！',1000);
                    return;
                }
                if(msgs.val){
                    if(msgs.val=='yes') addInVideoRTC();
                    else if(msgs.val=='no') $('#btn-dialogBox').dialogBox({
                            hasBtn: true, confirmValue:'额...',
                            title: '通知', content: "哈哈，对方不愿和你视频呢，气不气？",
                        });

                }else {//收到对方视频邀请
                    $('#btn-dialogBox').dialogBox({
                        hasClose: true,
                        hasBtn: true,
                        title: '视频聊天请求',
                        content: user_list[msgs.id]+"想和你视频聊天，同意不？",
                        confirmValue: '同意',
                        cancelValue: '不想',
                        confirm: function(){
                            iosocket.emit('chat_p2p',{what:'video',val:'yes',room: my_room});

                            video_p2p.hidden=video_me.hidden=false;
                            isInVideo=true;
                        },cancel:function(){iosocket.emit('chat_p2p',{what:'video',val:'no',room:my_room});}
                    });
                }
                break;
            default:break;
        }
    });
    iosocket.on('msg', function(msgs) {
        if(msgs.type=='img') addMsgPic(msgs.id,msgs.name,msgs.data);
        else addMsgRecord(msgs.id,msgs.name,msgs.msg);
    });
    iosocket.on('video_multi', function(data) {
        if(data.isNew){//有人新进入视频,直接向他发送offer
            console.log(user_list[data.id]+'加入群视频！');
            createRTCPeerConnection(data.id,createRemoteVideo(data.id),true);
        }else if(data.isQuit) {//有人退出
            console.log(user_list[data.id]+'退出群视频！');
            pcs[data.id].close();
            delete [data.id];
            $('#video_'+data.id).parent().remove();
        }else {//list,自己嘛什么都不干。
            console.log('已加入！');
            if(data.list.length<2)
                $('#btn-dialogBox').dialogBox({//询问一下
                    title: '通知', content: "暂时没有人加入群视频，请等待？",
                    hasClose:true, cancelValue:'哦哦'
                });
            isInVideo=true;
        }
    });
});